<?php

namespace app\common\service;

use app\common\model\OaWorkersModel;
use app\common\model\WorkOrderModel;
use app\common\model\OaWorkersLevelRecordModel;
use app\common\model\CustomerModel;
use app\common\model\OaWorkersExamModel;
use app\common\model\OaWorkersInvitationRecordModel;
use think\Controller;
use think\Db;

/**
 *   员工service
 * Class Workers
 * @package app\babyapi\controller
 */
class WorkersService {
	/*	 * *************************晋升******************************************* */

	/**
	 * 员工职位晋升
	 * @param int $workers_id 员工ID
	 */
	public static function upPosition($workers_id) {
		if (empty($workers_id)) {
			return false;
		}
		$oa_workers_model = new OaWorkersModel();

		$workers_info = $oa_workers_model->getOne(['workers_id' => $workers_id], 'position');
		//如果已经达到最顶级,不需要继续升级
		if ($workers_info['position'] == 5) {
			return false;
		}
		//开始升级
		switch ($workers_info['position']) {
			case 1:
				return WorkersService::position_second($workers_id);
				break;
			case 2:
				return WorkersService::position_third($workers_id);
				break;
			case 3:
				return WorkersService::position_fourth($workers_id);
				break;
			case 4:
				return WorkersService::position_fifth($workers_id);
				break;
			default:
				return false;
				break;
		}
	}

	/**
	 * 升级到营销经理
	 * 晋升条件:1-高级顾问提交3个合同工单，可以晋升
	 *          2-或发展9个下线，30个有效客户信息，可晋升
	 * @param int $workers_id 员工ID
	 */
	public static function position_second($workers_id) {
		$oa_workers_model = new OaWorkersModel();
		$work_order_model = new WorkOrderModel();
		$customer_model = new CustomerModel();

		/*		 * **********判断是否满足条件1******************* */
		//判断合同工单数量
		$join = [
			['contract c', 'a.contract_id=c.contract_id', 'left']
		];
		$where['workers_id'] = $workers_id;
		$where['c.status'] = 4;
		$contract_num = $work_order_model->getJoinCount($where, $join);
		if ($contract_num >= config('workers_up_position_rule')[2]['contract_num']) {
			//升级成功修改职位,新增晋升记录
			return WorkersService::upSuccess($workers_id, 1, '提交合同个数达到' . $contract_num);
		}

		/*		 * **********判断是否满足条件2******************* */
		$fans = $oa_workers_model->getCount(['workers_push_people' => $workers_id, 'workers_status' => 1, 'is_delete' => 0]); //下线数量
		$users = $customer_model->getCount(['source' => $workers_id, 'source_role' => 1, 'account_status' => 1, 'is_delete' => 0, 'last_be_related_expire_time' => ['>=', time()]]);
		if ($fans >= config('workers_up_position_rule')[2]['fans'] && $users >= config('workers_up_position_rule')[2]['users']) {
			//升级成功修改职位,新增晋升记录
			return WorkersService::upSuccess($workers_id, 1, '发展下线数量达到' . $fans . '且有效客户达到' . $users);
		}
		return false;
	}

	/**
	 * 升级到营销主任
	 * 晋升条件:1-发展n个下线，下线中满3人晋升为经理且个人6个月内签1单可以升级
	 * @param int $workers_id 员工ID
	 */
	public static function position_third($workers_id) {
		$oa_workers_model = new OaWorkersModel();
		$work_order_model = new WorkOrderModel();

		//判断合同工单数量
		$join = [
			['contract c', 'a.contract_id=c.contract_id', 'left']
		];
		$where['workers_id'] = $workers_id;
		$where['c.status'] = 4;
		$end = time();
		$start = $end - config('workers_up_position_rule')[3]['exam_cycle'] * 86400;
		$where['c.effect_time'] = ['between', [$start, $end]];
		$contract_num = $work_order_model->getJoinCount($where, $join); //近6个月签约合同数量
		$fans = $oa_workers_model->getCount(['workers_push_people' => $workers_id, 'workers_status' => 1, 'is_delete' => 0]); //下线数量
		$fans_second = $oa_workers_model->getCount(['workers_push_people' => $workers_id, 'workers_status' => 1, 'is_delete' => 0, 'position' => 2]); //下线经理数量
		if ($contract_num >= config('workers_up_position_rule')[3]['contract_num'] && $fans >= config('workers_up_position_rule')[3]['fans'] && $fans_second >= config('workers_up_position_rule')[3]['fans_second']) {
			//升级成功修改职位,新增晋升记录
			return WorkersService::upSuccess($workers_id, 2, '发展下线数量达到' . $fans . '且下线中经理人数达到' . $fans_second . '且近' . config('workers_up_position_rule')[3]['exam_cycle'] . '天签约' . $contract_num . '单');
		}
		return false;
	}

	/**
	 * 升级到总监
	 * 晋升条件:1-发展下线满3人晋升为主任且个人6个月内需签单，可晋升为总监
	 * @param int $workers_id 员工ID
	 */
	public static function position_fourth($workers_id) {
		$oa_workers_model = new OaWorkersModel();
		$work_order_model = new WorkOrderModel();
		//判断合同工单数量
		$join = [
			['contract c', 'a.contract_id=c.contract_id', 'left']
		];
		$where['workers_id'] = $workers_id;
		$where['c.status'] = 4;
		$end = time();
		$start = $end - config('workers_up_position_rule')[4]['exam_cycle'] * 86400;
		$where['c.effect_time'] = ['between', [$start, $end]];
		$contract_num = $work_order_model->getJoinCount($where, $join); //近6个月签约合同数量
		$fans = $oa_workers_model->getCount(['workers_push_people' => $workers_id, 'workers_status' => 1, 'is_delete' => 0]); //下线数量
		$fans_second = $oa_workers_model->getCount(['workers_push_people' => $workers_id, 'workers_status' => 1, 'is_delete' => 0, 'position' => 3]); //下线主任数量
		if ($contract_num >= config('workers_up_position_rule')[4]['contract_num'] && $fans >= config('workers_up_position_rule')[4]['fans'] && $fans_second >= config('workers_up_position_rule')[4]['fans_second']) {
			//升级成功修改职位,新增晋升记录
			return WorkersService::upSuccess($workers_id, 3, '发展下线数量达到' . $fans . '且下线中主任人数达到' . $fans_second . '且近' . config('workers_up_position_rule')[3]['exam_cycle'] . '天签约' . $contract_num . '单');
		}
		return false;
	}

	/**
	 * 升级到合伙人
	 * 晋升条件:1-发展线下满4个总监，可晋升为合伙人
	 * @param int $workers_id 员工ID
	 */
	public static function position_fifth($workers_id) {
		$oa_workers_model = new OaWorkersModel();
		$fans = $oa_workers_model->getCount(['workers_push_people' => $workers_id, 'workers_status' => 1, 'is_delete' => 0]); //下线数量
		$fans_second = $oa_workers_model->getCount(['workers_push_people' => $workers_id, 'workers_status' => 1, 'is_delete' => 0, 'position' => 4]); //下线总监数量
		if ($fans >= config('workers_up_position_rule')[5]['fans'] && $fans_second >= config('workers_up_position_rule')[5]['fans_second']) {
			//升级成功修改职位,新增晋升记录
			return WorkersService::upSuccess($workers_id, 4, '发展下线数量达到' . $fans . '且下线中总监人数达到' . $fans_second);
		}
		return false;
	}

	//晋升成功
	public static function upSuccess($workers_id, $old_postion, $remarks = '') {
		$oa_workers_model = new OaWorkersModel();
		$oa_workers_level_record_model = new OaWorkersLevelRecordModel();
		//新增晋升记录
		$record['workers_id'] = $workers_id;
		$record['current_level'] = $old_postion;
		$record['promotion_level'] = $old_postion + 1;
		$record['create_time'] = time();
		$record['type'] = 1;
		$record['remarks'] = $remarks;
		$res = $oa_workers_level_record_model->add($record);
		//修改员工等级
		$res2 = $oa_workers_model->edit(['workers_id' => $workers_id], ['position' => $record['promotion_level']]);
		//判断是否等级超越推荐人,超过则自动解绑
		$workers_info = $oa_workers_model->getOne(['workers_id' => $workers_id], 'workers_push_people');
		if (!empty($workers_info) && !empty($workers_info['workers_push_people'])) {
			$workers_push_people = $oa_workers_model->getOne(['workers_id' => $workers_info['workers_push_people']], 'position');
			if (!empty($workers_push_people) && $workers_push_people['position'] <= $record['promotion_level']) {
				$oa_workers_invitation_record = new OaWorkersInvitationRecordModel();
				$oa_workers_invitation_record->edit(['workers_id' => $workers_info['workers_push_people'], 'invite_workers_id' => $workers_id, 'status' => 3], ['untying_time' => time(), 'status' => 6, 'remarks' => '越级自动解绑']); //修改绑定状态
				$oa_workers_model->edit(['workers_id' => $workers_id], ['workers_push_people' => 0]); //重置推荐人
			}
		}
		return $res && $res2;
	}

	/**
	 * 升级到下一等级情况说明
	 * @param type $workers_id 员工ID
	 * @param type $old_postion 当前等级
	 * @return type
	 */
	public static function nextPosition($workers_id, $old_postion) {
		$oa_workers_model = new OaWorkersModel();
		$work_order_model = new WorkOrderModel();
		$customer_model = new CustomerModel();
		$arr = [];
		switch ($old_postion) {
			case 1:
				/**
				 * 升级到营销经理
				 * 晋升条件:1-高级顾问提交3个合同工单，可以晋升
				 *          2-或发展9个下线，30个有效客户信息，可晋升
				 */
				/*				 * **********判断是否满足条件1******************* */
				//判断合同工单数量
				$join = [
					['contract c', 'a.contract_id=c.contract_id', 'left']
				];
				$where['workers_id'] = $workers_id;
				$where['c.status'] = 4;
				$contract_num = $work_order_model->getJoinCount($where, $join);
				$result['name'] = '签单数';
				$result['complete'] = $contract_num;
				$result['target'] = config('workers_up_position_rule')[2]['contract_num'];
				$arr[] = $result;
				/*				 * **********判断是否满足条件2******************* */
				$fans = $oa_workers_model->getCount(['workers_push_people' => $workers_id, 'workers_status' => 1, 'is_delete' => 0]); //下线数量
				$users = $customer_model->getCount(['source' => $workers_id, 'source_role' => 1, 'account_status' => 1, 'is_delete' => 0, 'last_be_related_expire_time' => ['>=', time()]]);
				$result['name'] = '团队人员';
				$result['complete'] = $fans;
				$result['target'] = config('workers_up_position_rule')[2]['fans'];
				$arr[] = $result;
				$result['name'] = '有效客户';
				$result['complete'] = $users;
				$result['target'] = config('workers_up_position_rule')[2]['users'];
				$arr[] = $result;
				break;
			case 2:
				/**
				 * 升级到营销主任
				 * 晋升条件:1-发展n个下线，下线中满3人晋升为经理且个人6个月内签1单可以升级
				 */
				//判断合同工单数量
				$join = [
					['contract c', 'a.contract_id=c.contract_id', 'left']
				];
				$where['workers_id'] = $workers_id;
				$where['c.status'] = 4;
				$end = time();
				$start = $end - config('workers_up_position_rule')[3]['exam_cycle'] * 86400;
				$where['c.effect_time'] = ['between', [$start, $end]];
				$contract_num = $work_order_model->getJoinCount($where, $join); //近6个月签约合同数量
				$result['name'] = '签单数';
				$result['complete'] = $contract_num;
				$result['target'] = config('workers_up_position_rule')[3]['contract_num'];
				$arr[] = $result;

				$fans = $oa_workers_model->getCount(['workers_push_people' => $workers_id, 'workers_status' => 1, 'is_delete' => 0]); //下线数量
				$result['name'] = '团队人员';
				$result['complete'] = $fans;
				$result['target'] = config('workers_up_position_rule')[3]['fans'];
				$arr[] = $result;

				$fans_second = $oa_workers_model->getCount(['workers_push_people' => $workers_id, 'workers_status' => 1, 'is_delete' => 0, 'position' => 2]); //下线经理数量
				$result['name'] = '团队经理';
				$result['complete'] = $fans_second;
				$result['target'] = config('workers_up_position_rule')[3]['fans_second'];
				$arr[] = $result;
				break;
			case 3:
				/**
				 * 升级到总监
				 * 晋升条件:1-发展下线满3人晋升为主任且个人6个月内需签单，可晋升为总监
				 */
				//判断合同工单数量
				$join = [
					['contract c', 'a.contract_id=c.contract_id', 'left']
				];
				$where['workers_id'] = $workers_id;
				$where['c.status'] = 4;
				$end = time();
				$start = $end - config('workers_up_position_rule')[4]['exam_cycle'] * 86400;
				$where['c.effect_time'] = ['between', [$start, $end]];
				$contract_num = $work_order_model->getJoinCount($where, $join); //近6个月签约合同数量
				$result['name'] = '签单数';
				$result['complete'] = $contract_num;
				$result['target'] = config('workers_up_position_rule')[4]['contract_num'];
				$arr[] = $result;

				$fans = $oa_workers_model->getCount(['workers_push_people' => $workers_id, 'workers_status' => 1, 'is_delete' => 0]); //下线数量
				$result['name'] = '团队人员';
				$result['complete'] = $fans;
				$result['target'] = config('workers_up_position_rule')[4]['fans'];
				$arr[] = $result;

				$fans_second = $oa_workers_model->getCount(['workers_push_people' => $workers_id, 'workers_status' => 1, 'is_delete' => 0, 'position' => 3]); //下线主任数量
				$result['name'] = '团队主任';
				$result['complete'] = $fans_second;
				$result['target'] = config('workers_up_position_rule')[4]['fans_second'];
				$arr[] = $result;
				break;
			case 4:
				/**
				 * 升级到合伙人
				 * 晋升条件:1-发展线下满4个总监，可晋升为合伙人
				 */
				$fans = $oa_workers_model->getCount(['workers_push_people' => $workers_id, 'workers_status' => 1, 'is_delete' => 0]); //下线数量
				$result['name'] = '团队人员';
				$result['complete'] = $fans;
				$result['target'] = config('workers_up_position_rule')[5]['fans'];
				$arr[] = $result;
				$fans_second = $oa_workers_model->getCount(['workers_push_people' => $workers_id, 'workers_status' => 1, 'is_delete' => 0, 'position' => 4]); //下线总监数量
				$result['name'] = '团队总监';
				$result['complete'] = $fans_second;
				$result['target'] = config('workers_up_position_rule')[5]['fans_second'];
				$arr[] = $result;
				break;
			case 5:
				break;

			default:
				break;
		}


		return $arr;
	}

	/**	 * ************************考核******************************************* */

	/**
	 * 员工考核
	 * 在考核时间内签单数是否达标
	 * $lists 考核列表
	 */
	public static function examPosition($lists) {
		$oa_workers_model = new OaWorkersModel();
		$work_order_model = new WorkOrderModel();
		$oa_workers_level_record_model = new OaWorkersLevelRecordModel();
		$oa_workers_exam_model = new OaWorkersExamModel();
		file_put_contents('./position_exam.txt', date('Y-m-d H:i:s') . '开始考核' . PHP_EOL, FILE_APPEND | LOCK_EX);
		// 开始事务
		Db::startTrans();
		try {
			foreach ($lists as $k => $v) {
				$workers_info = $oa_workers_model->getOne(['workers_id' => $v['workers_id']], 'position');
				//如果已经达到最低/高级,不需要继续降级考核
				if ($workers_info['position'] == 1 || $workers_info['position'] == 5) {
					$edit['status'] = 2;
					$edit['exam_time'] = time();
					$edit['result'] = 3;
					$oa_workers_exam_model->edit(['id' => $v['id']], $edit); //编辑考核状态
					//新增考核记录
					$add['workers_id'] = $v['workers_id'];
					$add['start_time'] = time();
					$add['end_time'] = $add['start_time'] + config('workers_exam_position_rule')[$workers_info['position']]['exam_cycle'] * 86400;
					$add['status'] = 1;
					$add['create_time'] = time();
					$oa_workers_exam_model->add($add);
					continue;
				}
				$join = [
					['contract c', 'a.contract_id=c.contract_id', 'left']
				];
				$where['workers_id'] = $v['workers_id'];
				$where['c.status'] = 4;
				$where['c.effect_time'] = ['between', [$v['start_time'], $v['end_time']]];
				$contract_num = $work_order_model->getJoinCount($where, $join); //近6个月签约合同数量
				$edit['result'] = 2;
				if ($contract_num >= config('workers_exam_position_rule')[$workers_info['position']]['contract_num']) {//考核通过
					$edit['result'] = 1;
				}
				$edit['status'] = 2;
				$edit['exam_time'] = time();
				$oa_workers_exam_model->edit(['id' => $v['id']], $edit); //编辑考核状态
				//新增考核记录
				$add['workers_id'] = $v['workers_id'];
				$add['start_time'] = time();
				$add['end_time'] = $add['start_time'] + config('workers_exam_position_rule')[$workers_info['position']]['exam_cycle'] * 86400;
				$add['status'] = 1;
				$add['create_time'] = time();
				$oa_workers_exam_model->add($add);
				//如果考核不通过降级
				if ($edit['result'] == 2) {
					//新增职位记录
					$record['workers_id'] = $v['workers_id'];
					$record['current_level'] = $workers_info['position'];
					$record['promotion_level'] = $workers_info['position'] - 1;
					$record['create_time'] = time();
					$record['type'] = 2;
					$record['remarks'] = config('workers_exam_position_rule')[$workers_info['position']]['exam_cycle'] . '天签约数量未达标仅' . $contract_num . '单';
					$oa_workers_level_record_model->add($record);
					//修改员工等级
					$oa_workers_model->edit(['workers_id' => $v['workers_id']], ['position' => $record['promotion_level']]);
					file_put_contents('./position_exam.txt', date('Y-m-d H:i:s') . $v['workers_id'] . '考核不通过', FILE_APPEND | LOCK_EX);
				}
			}
			file_put_contents('./position_exam.txt', date('Y-m-d H:i:s') . '考核成功' . PHP_EOL, FILE_APPEND | LOCK_EX);
			// 事务提交
			Db::commit();
			echo date('Y-m-d H:i:s') . '考核成功';
		} catch (\PDOException $ex) {
			// 事务回滚
			Db::rollback();
			file_put_contents('./position_exam.txt', date('Y-m-d H:i:s') . '考核失败' . PHP_EOL, FILE_APPEND | LOCK_EX);
			echo date('Y-m-d H:i:s') . '考核失败';
		}
	}

}
